﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Cofe.Data.Utils
{
    public static class DbContextExtensions
    {
        //http://weblogs.asp.net/ricardoperes/archive/2012/03/19/entity-framework-code-first-get-entities-from-local-cache-or-the-database.aspx
        public static IQueryable<T> LocalOrDatabase<T>(this DbContext context, Expression<Func<T, Boolean>> expression) where T : class
        {
            IEnumerable<T> localResults = context.Set<T>().Local.Where(expression.Compile());

            if (localResults.Any() == true)
            {
                return (localResults.AsQueryable());
            }

            IQueryable<T> databaseResults = context.Set<T>().Where(expression);
            return (databaseResults);
        }


    }
}
